package com.lychee.binderdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Lychee of on 2017/10/24 14:02.
 * <p>
 * Author: Hejingzhou
 * <p>
 * Email: tcowork@163.com
 */
public class BinderService extends Service {

    private final String TAG = this.getClass().getSimpleName();
    public static final int REPORT_CODE = 0;
    private HandlerMethod mReporter;

    public BinderService() {
        this.mReporter = new HandlerMethod();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mReporter;
    }

    public final class HandlerMethod extends Binder implements IHandlerMethod {


        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
            switch (code) {
                /**
                 * 可能多个客户端进行访问这个Service
                 */
                case REPORT_CODE:
                    data.enforceInterface("reporter");

//                    User userdata = data.readBundle().getParcelable("userdata");
//                    System.out.println(userdata.toString());

                    String valuesString = data.readString();
                    Log.i(TAG, "Service收到String字符串\t" + valuesString);

                    int valuesInt = data.readInt();
                    Log.i(TAG, "Service 收到的Int 类型数据\t" + valuesInt);

                    //处理后的数据
                    int result = handler(valuesInt);

                    //将处理完的数据进行传出去
                    reply.writeInterfaceToken("reporter");
                    reply.writeInt(result);
                    return true;
            }
            return super.onTransact(code, data, reply, flags);
        }

        /**
         * Service 获得Client 来的数据进行处理
         *
         * @param num
         * @return
         */
        @Override
        public int handler(int num) {

            return num + 100;
        }
    }

}
